import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ReservationDao {
    // 预约座位
    public void reserve(int studentId, int seatNo, Date time) throws SQLException {
        String sql = "INSERT INTO reservation (student_id, seat_no, reserve_time) VALUES (?, ?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, studentId);
            ps.setInt(2, seatNo);
            ps.setTimestamp(3, new java.sql.Timestamp(time.getTime()));
            ps.executeUpdate();
        }
    }

    // 取消预约
    public void cancel(int studentId, int seatNo, Date time) throws SQLException {
        String sql = "DELETE FROM reservation WHERE student_id = ? AND seat_no = ? AND reserve_time = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, studentId);
            ps.setInt(2, seatNo);
            ps.setTimestamp(3, new java.sql.Timestamp(time.getTime()));
            ps.executeUpdate();
        }
    }

    // 查询指定时间已预约的座位
    public List<Integer> getReservedSeats(Date time) throws SQLException {
        List<Integer> reservedSeats = new ArrayList<>();
        String sql = "SELECT seat_no FROM reservation WHERE reserve_time = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setTimestamp(1, new java.sql.Timestamp(time.getTime()));
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                reservedSeats.add(rs.getInt("seat_no"));
            }
        }
        return reservedSeats;
    }

    // 查询学生的所有预约记录
    public List<Reservation> getMyReservations(int studentId) throws SQLException {
        List<Reservation> reservations = new ArrayList<>();
        String sql = "SELECT * FROM reservation WHERE student_id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, studentId);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                Reservation res = new Reservation();
                res.setId(rs.getInt("id"));
                res.setStudentId(rs.getInt("student_id"));
                res.setSeatNo(rs.getInt("seat_no"));
                res.setReserveTime(rs.getTimestamp("reserve_time"));
                reservations.add(res);
            }
        }
        return reservations;
    }
}